package com.company.cloud.product.modules.mgr.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.auth.annotation.StaffLogc;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.log.annotation.SysLog;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.product.constant.ProductErrorEnum;
import com.company.cloud.product.modules.api.response.Sku;
import com.company.cloud.product.modules.base.entity.*;
import com.company.cloud.product.modules.base.service.*;
import com.company.cloud.product.modules.cache.service.ProductInfoCacheService;
import com.company.cloud.product.modules.mgr.controller.req.*;
import com.company.cloud.product.modules.mgr.controller.resp.ProductStockModel;
import com.company.cloud.product.modules.mgr.models.ComeModel;
import com.company.cloud.product.modules.mgr.models.OutModel;
import com.company.cloud.product.modules.mgr.service.ProductStockMgrService;
import com.company.cloud.product.modules.mgr.utils.ProductConvertUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;

/**
 * 商品库存管理
 */
@Authc
@RestController
@RequestMapping("/mgr/prd/stock")
@Api(tags = "Product_Mgr_商品库存管理")
public class ProductStockMgrController {

    @Autowired
    private ProductStockInfoService productStockInfoService;

    @Autowired
    private ProductStockMgrService productStockMgrService;

    @Autowired
    private ProductInfoCacheService productInfoCacheService;

    @Autowired
    private ComeOrderService comeOrderService;

    @Autowired
    private ComeOrderItemService comeOrderItemService;

    @Autowired
    private OutOrderService outOrderService;

    @Autowired
    private OutOrderItemService outOrderItemService;

//	@Autowired
//	private UserRoleDeptGroupService userRoleDeptGroupService;

    @PostMapping("/query")
    @SysLog("商品库存查询")
    @ApiOperation(value = "商品库存查询", response = BaseResult.class)
    public BaseResult query(@RequestBody ProductStockQuery4PageParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        IPage<ProductStockInfo> page = productStockInfoService.page(new Page<>(params.getPage(), params.getRows()),
                new QueryWrapper<ProductStockInfo>()
                        .eq("company_no", userInfo.getCompanyNo())
                        .eq(CheckUtils.hasText(params.getProductNo()), "product_no", params.getProductNo())
                        .eq(CheckUtils.hasText(params.getSkuNo()), "sku_no", params.getSkuNo())
                        .orderByDesc("product_no", "sku_no")
        );
        if (page == null || CollectionUtils.isEmpty(page.getRecords())) {
            return BaseResult.ok();
        }
        Set<String> skuNos = new HashSet<String>();
        page.getRecords().forEach(item -> {
            skuNos.add(item.getSkuNo());
        });
        Map<String, Sku> skuMap = productInfoCacheService.getSkuByCache2Map(skuNos);

        IPage<ProductStockModel> data = page.convert(new Function<ProductStockInfo, ProductStockModel>() {
            @Override
            public ProductStockModel apply(ProductStockInfo entity) {
                ProductStockModel model = new ProductStockModel();
                model.setId(entity.getId());
                model.setCustNo(entity.getCustNo());
                model.setProductNo(entity.getProductNo());
                model.setSkuNo(entity.getSkuNo());
                model.setNum(entity.getNum());
                model.setFreezeNum(entity.getFreezeNum());
                Sku sku = skuMap.get(entity.getSkuNo());
                if (sku != null) {
                    model.setSku(sku);
                    model.setProductName(sku.getName());
                    model.setProductImg(sku.getImage());
                }
//				if(YNEnum.YES.getCode().equals(params.getIsUser())) {
//					Integer _userId=Integer.parseInt(entity.getCustNo());
//					UserInfoModel user= userMap.get(_userId);
//					if(user!=null) {
//						model.setCustName(user.getNickName());
//					}
//				}
                return model;
            }
        });
        return BaseResult.ok(data);
    }


    //---------------------------------------------------------Come
    @PostMapping("/queryComeOrder")
    @SysLog("查询商品入库单")
    @ApiOperation(value = "查询商品入库单", response = ComeModel.class)
    public BaseResult queryComeOrder(@RequestBody ProductStockComeQuery4PageParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        IPage<ComeOrder> page = comeOrderService.page(new Page<>(params.getPage(), params.getRows()),
                new QueryWrapper<ComeOrder>()
                        .eq("company_no", userInfo.getCompanyNo())
                        .eq(StringUtils.hasText(params.getSn()), "sn", params.getSn())
                        .orderByDesc("order_date")
        );
        if (page == null || CollectionUtils.isEmpty(page.getRecords())) {
            return BaseResult.ok();
        }

        List<String> snList = new ArrayList<String>();
        page.getRecords().forEach(item -> {
            snList.add(item.getSn());
        });

        List<ComeOrderItem> orderItemList = comeOrderItemService.list(new QueryWrapper<ComeOrderItem>().in("come_sn", snList));


        IPage<ComeModel> data = page.convert(new Function<ComeOrder, ComeModel>() {
            @Override
            public ComeModel apply(ComeOrder order) {
                ComeModel obj = ProductConvertUtils.getComeModel(order, orderItemList);
                return obj;
            }
        });
        return BaseResult.ok(data);

    }

    @GetMapping("/getComeOrder")
    @SysLog("查看商品入库单")
    @ApiOperation(value = "查看商品入库单", response = ComeModel.class)
    public BaseResult getComeOrder(@RequestParam("sn") String sn) {
        ComeOrder order = comeOrderService.getById(sn);
        if (order == null) {
            throw new BusinessException(ProductErrorEnum.Stock_Come_Order_NotExist);
        }
        List<ComeOrderItem> orderItems = comeOrderItemService.list(new QueryWrapper<ComeOrderItem>().eq("come_sn", sn));
        ComeModel data = ProductConvertUtils.getComeModel(order, orderItems);
        return BaseResult.ok(data);
    }

    @PostMapping("/saveComeOrder")
    @SysLog("新增商品入库单")
    @ApiOperation(value = "新增商品入库单", response = BaseResult.class)
    @StaffLogc(title = "新增商品入库单", action = "新增商品入库单", actionAdo = "商品出库单")
    public BaseResult saveComeOrder(@RequestBody ProductStockComeSaveParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        productStockMgrService.saveComeOrder(params, userInfo);
        return BaseResult.ok();
    }

    //---------------------------------------------------------Out

    @PostMapping("/queryOutOrder")
    @SysLog("查询商品出库单")
    @ApiOperation(value = "查询商品出库单", response = OutModel.class)
    public BaseResult queryOutOrder(@RequestBody ProductStockOutQuery4PageParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        IPage<OutOrder> page = outOrderService.page(new Page<>(params.getPage(), params.getRows()),
                new QueryWrapper<OutOrder>()
                        .eq("company_no", userInfo.getCompanyNo())
                        .eq(StringUtils.hasText(params.getSn()), "sn", params.getSn())
                        .orderByDesc("order_date")
        );
        if (page == null || CollectionUtils.isEmpty(page.getRecords())) {
            return BaseResult.ok();
        }
        List<String> snList = new ArrayList<String>();
        page.getRecords().forEach(item -> {
            snList.add(item.getSn());
        });
        List<OutOrderItem> orderItemList = outOrderItemService.list(new QueryWrapper<OutOrderItem>().in("out_sn", snList));

        IPage<OutModel> data = page.convert(new Function<OutOrder, OutModel>() {
            @Override
            public OutModel apply(OutOrder order) {
                OutModel obj = ProductConvertUtils.getOutModel(order, orderItemList);
                return obj;
            }
        });
        return BaseResult.ok(data);
    }

    @GetMapping("/getOutOrder")
    @SysLog("查看商品出库单")
    @ApiOperation(value = "查看商品出库单", response = OutModel.class)
    public BaseResult getOutOrder(@RequestParam("sn") String sn) {
        OutOrder order = outOrderService.getById(sn);
        if (order == null) {
            throw new BusinessException(ProductErrorEnum.Stock_Out_Order_NotExist);
        }
        List<OutOrderItem> orderItems = outOrderItemService.list(new QueryWrapper<OutOrderItem>().eq("out_sn", sn));
        OutModel data = ProductConvertUtils.getOutModel(order, orderItems);
        return BaseResult.ok(data);
    }

    @PostMapping("/saveOutOrder")
    @SysLog("新增商品出库单")
    @ApiOperation(value = "新增商品出库单", response = BaseResult.class)
    @StaffLogc(title = "新增商品出库单", action = "新增商品出库单", actionAdo = "商品出库单")
    public BaseResult saveOutOrder(@RequestBody ProductStockOutSaveParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        productStockMgrService.saveOutOrder(params, userInfo);
        return BaseResult.ok();
    }


}
